const SUCCESS_STATUS = 200;// 默认成功状态
import axios from 'axios'
import { ElNotification , ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from '@/utils/zone'
import cache from '@/plugins/cache'
import { saveAs } from 'file-saver'
import useUserStore from '@/store/modules/user'
import Conf from '@/utils/conf'

let downloadLoadingInstance;
// 是否显示重新登录
export const isRelogin = { show: false };

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.withCredentials = true; // 允许携带cookie
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: Conf.VITE_APP_BASE_API,
  // 超时
  timeout: 100000
})

// request拦截器
service.interceptors.request.use(
  config => {
    const headers = config.headers || {};
    // 是否需要设置 token,默认为true
    const isToken = !headers.isToken
    // 是否需要防止数据重复提交
    const isRepeatSubmit = !headers.repeatSubmit
    if (isToken && getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      const url = config.url + '?' + tansParams(config.params);
      config.params = {};
      config.url = url;
    }
    if (isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
      const requestObj = {
        url: config.url,
        data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
        time: new Date().getTime()
      }
      const sessionObj = cache.session.getJSON('sessionObj')
      if (!sessionObj) {
        cache.session.setJSON('sessionObj', requestObj)
      } else {
        const s_url = sessionObj.url;                // 请求地址
        const s_data = sessionObj.data;              // 请求数据
        const s_time = sessionObj.time;              // 请求时间
        const interval = 200;              // 间隔时间(ms)，小于此时间视为重复提交
        if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
          const message = '数据正在处理，请勿频繁操作';
          return Promise.reject(new Error(message))
        } else {
          cache.session.setJSON('sessionObj', requestObj)
        }
      }
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)
async function handle401() {
  if (!isRelogin.show) {
    isRelogin.show = true;
    try {
      await ElMessageBox.confirm("登录状态已过期，您可以继续留在该页面，或者重新登录", "系统提示", {
        confirmButtonText: "重新登录",
        cancelButtonText: "取消",
        type: "warning",
      });
      await useUserStore().logOut();
      location.href = Conf.VITE_STATIC_BASE_URI + window.location.hash;
      location.reload();
    } finally {
      isRelogin.show = false;
    }
  }
  return Promise.reject(new Error("无效的会话，或者会话已过期，请重新登录。"));
}
function handleError(code, msg) {
  switch (code) {
    case 401:
      return handle401();
    case 500:
      ElMessage({ message: msg, type: "error", dangerouslyUseHTMLString: true });
      break;
    case 601:
      ElMessage({ message: msg, type: "warning" });
      break;
    default:
      ElNotification.error({ title: msg });
      break;
  }
  return Promise.reject(new Error(msg));
}
// 响应拦截器
service.interceptors.response.use(
  async res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || SUCCESS_STATUS;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode["default"];
    // 二进制数据则直接返回
    if (code === SUCCESS_STATUS || res.request.responseType === "blob" || res.request.responseType === "arraybuffer") {
      return Promise.resolve(res.data);
    }
    return handleError(code, msg);
  },
  error => {
    const { message } = error;
    const msg = ref("");
    switch (true) {
      case message.includes("Network Error"):
        msg.value = "后端接口连接异常";
        break;
      case message.includes("timeout"):
        msg.value = "系统接口请求超时";
        break;
      case message.includes("Request failed with status code"):
        msg.value = `系统接口${message.slice(ERROR_MESSAGE)}异常`;
        break;
      default:
        msg.value = "未知错误";
    }
    return Promise.reject(new Error(msg.value));
  },
);

// 通用下载方法
export async function download(url, params, filename, config) {
  downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)" });

  try {
    const response = await service.post(url, params, {
      transformRequest: [params => tansParams(params)],
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
      ...config,
    });

    const isBlob = blobValidate(response);
    if (isBlob) {
      const blob = new Blob([response]);
      saveAs(blob, filename);
    } else {
      const resText = await response.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
      ElMessage.error(errMsg);
    }
  } catch (error) {
    ElMessage.error("下载文件出现错误，请联系管理员！");
  } finally {
    downloadLoadingInstance.close();
  }
}

export default service;
